package com.sc.chsdata.Schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.chsdata.entity.ChsExplainLog;
import com.sc.chsdata.entity.Fctd2020;
import com.sc.chsdata.mapper.ChsExplainLogMapper;
import com.sc.chsdata.mapper.Fctd2020Mapper;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Configuration
@Component
@CommonsLog
public class ChsDataExplainTask {
    private static DecimalFormat fmt = new DecimalFormat("0");


    @Autowired
    private Fctd2020Mapper fctd2020Mapper;
    @Autowired
    private ChsExplainLogMapper chsExplainLogMapper;

    @Value("${chs.path}")
    private String path ;
    @Value("${chs.newpath}")
    private String newpath ;
    @Scheduled(cron = "0 * * * * *")//每分钟执行一次读取
    public  void explainData() throws ParseException {
        folderMethod2(path);
        System.out.println(path);
    }

    //解析文件返回文本
    public static String  readfile(File file){
        StringBuilder sb = new StringBuilder();
        FileReader fileReader = null;
        BufferedReader br = null;
        if(file.exists()){

            try {
                fileReader = new FileReader(file);
                br = new BufferedReader(fileReader);
                String s = null;
                while((s=br.readLine())!=null){
                    sb.append(s);
                }



            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close();
                    fileReader.close();
                    ;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            System.out.println("文件不存在");//
        }
        System.out.println("文件内容为============>"+sb.toString());
        return sb.toString();
    }



    //遍历文件夹
    public  void folderMethod2(String path) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd\'T\'HH:mm:ss");
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        System.out.println("文件夹:" + file2.getAbsolutePath());
                        folderMethod2(file2.getAbsolutePath());
                    } else {
                        try {

                            System.out.println("文件:" + file2.getAbsolutePath());
                            String dataJson = readfile(file2);
                            JSONObject jsonObject = JSON.parseObject(dataJson);
                            String sn = (String) jsonObject.get("SN");

                            if ("21ODNCABLENULL000000".equals(sn)) {//没有正确的SN不解析移动文件
                                ChsExplainLog log = new ChsExplainLog();
                                log.setCreateDate(new Date());
                                log.setDescription("文件没有解析");
                                log.setPass(1);
                                log.setFilename(file2.getAbsolutePath());
                                chsExplainLogMapper.insert(log);
                                System.out.println("不解析的SN为：" + sn);

                            } else {
                                System.out.println("解析的SN为：" + sn);
                                String operID = jsonObject.getString("OperID");//操作员ID
                                String result = jsonObject.getString("Result");//结果，应该是失败或者成功
                                String startTime = jsonObject.getString("StartTime");//开始时间
                                String stopTime = jsonObject.getString("StopTime");//结束时间
                                JSONArray result2Array = jsonObject.getJSONArray("Result2Array");
                                if (result2Array.size() == 5) {//长度为5才解析
                                    //第四个是嘉惠测试仪的测试数据
                                    JSONArray result3Array = result2Array.getJSONObject(3).getJSONArray("Result3Array");
                                    System.out.println("result3Array数组的大小为:" + result3Array.size());

                                    double il1310 = 0;
                                    double rl1310 = 0;
                                    double il1550 = 0;
                                    double rl1550 = 0;//
                                    String il1310Stan = "";
                                    String rl1310Stan = "";
                                    String il1550Stan = "";
                                    String rl1550Stan = "";
                                    String orderId = "";
                                    for (int i = 0; i < result3Array.size(); i++) {
                                        //取IL1310 IL1550 RL1310 RL1550//
                                        JSONObject result3 = result3Array.getJSONObject(i);//每个结果集
                                        String SubTestItemName = result3.getString("SubTestItemName");

                                        switch (SubTestItemName) {
                                            case "R101:lil 1310 [1][1]":
                                                il1310 = Double.parseDouble(result3.getString("ResultDesc")) * 1000;
                                                il1310Stan = result3.getString("SN");
                                                break;
                                            case "R101:lrl 1310 [1][1]":
                                                rl1310 = Double.parseDouble(result3.getString("ResultDesc")) * 1000;
                                                rl1310Stan = result3.getString("SN");
                                                break;
                                            case "R101:hil 1550 [1][1]":
                                                il1550 = Double.parseDouble(result3.getString("ResultDesc")) * 1000;
                                                il1550Stan = result3.getString("SN");
                                                break;
                                            case "R101:hrl 1550 [1][1]":
                                                rl1550 = Double.parseDouble(result3.getString("ResultDesc")) * 1000;
                                                rl1550Stan = result3.getString("SN");
                                                break;
                                            case "R101:Workorder":
                                                orderId = result3.getString("ResultDesc");
                                                break;
                                            default:
                                                break;
                                        }


                                    }
                                    System.out.println(il1310 + ":" + rl1310 + ":" + il1550 + ":" + rl1550);
                                    //保存数据到数据库里面
                                    Fctd2020 fctd = new Fctd2020();
                                    fctd.setTestdate(new Timestamp(sdf.parse(startTime).getTime()));
                                    fctd.setStd(new Timestamp(sdf.parse(stopTime).getTime()));
                                    fctd.setTv1(Integer.parseInt(fmt.format(il1310)));
                                    fctd.setTv2(Integer.parseInt(fmt.format(il1550)));
                                    fctd.setTv3(Integer.parseInt(fmt.format(rl1310)));
                                    fctd.setTv4(Integer.parseInt(fmt.format(rl1550)));
                                    fctd.setPass("0".equals(result)?1:0);//1为通过，为失败
                                    fctd.setTwitem("IL1310,RL1310,IL1550,RL1550,");
                                    fctd.setTwl(il1310Stan + "-" + rl1310 + "-" + il1550 + "-" + rl1550);
                                    fctd.setTwkname(operID);
                                    fctd.setTestcode("Normal");
                                    fctd.setTestid(1);
                                    fctd.setOrderid(orderId);
                                    fctd.setOrdersort("1");
                                    fctd.setScancode(sn);
                                    fctd.setExplaintime(new Timestamp(new Date().getTime()));
                                    fctd.setTid(1);
                                    fctd2020Mapper.insert(fctd);
                                    //记录到日志表
                                    ChsExplainLog log = new ChsExplainLog();
                                    log.setCreateDate(new Date());
                                    log.setDescription("解析文件成功");
                                    log.setPass(0);
                                    log.setFilename(file2.getAbsolutePath());
                                    chsExplainLogMapper.insert(log);



                                }
                            }
                            System.out.println("R1Guid=========》" + jsonObject.get("R1Guid"));


                            //移动文件,D盘移动到E盘
                            String newPath = newpath + file2.getAbsolutePath().substring(1);
                            File newFile = new File(newPath);
                            try {
                                FileUtils.copyFile(file2, newFile);
                                //删除原文件
                                FileUtils.forceDelete(file2);//
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            //记录到日志
                            ChsExplainLog log = new ChsExplainLog();
                            log.setCreateDate(new Date());
                            log.setDescription("解析文件失败");
                            log.setPass(1);
                            log.setFilename(file2.getAbsolutePath());
                            chsExplainLogMapper.insert(log);
                            //移动文件,D盘移动到E盘
                            String newPath = newpath + file2.getAbsolutePath().substring(1);
                            File newFile = new File(newPath);
                            try {
                                FileUtils.copyFile(file2, newFile);
                                //删除原文件
                                FileUtils.forceDelete(file2);//
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                            continue;
                        }

                    }
                }
            } else {
                System.out.println("文件不存在!");
            }
        }
    }


}
